package org.github.choviwu.example.common.web;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.github.choviwu.example.common.util.AESUtil;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;

@RestControllerAdvice(basePackages = "org.choviwu")
@Slf4j
public class ApiRequest implements RequestBodyAdvice {


    @Override
    public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object handleEmptyBody(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {

        return o;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException {
//        try {
//            if(methodParameter.getMethod().isAnnotationPresent(MyConvert.class)){
//                Object obj = aClass.newInstance();
//                JsonConvert convert = new RequestJsonConvert();
//                convert.convert(obj);
//                return new DHttpInputMessage(httpInputMessage);
//            }
//        }catch (Exception e){ }
        return httpInputMessage;
    }

    @Override
    public Object afterBodyRead(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter,
                                Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return o;
    }

    public static class DHttpInputMessage implements HttpInputMessage{
        private HttpHeaders headers;

        private InputStream body;
        private String key = "1fdsv3choviwu@#~";
        public DHttpInputMessage(HttpInputMessage inputMessage) throws IOException {
            this.headers = inputMessage.getHeaders();
            this.body = IOUtils.toInputStream(AESUtil.getInstance().decrypt(IOUtils.toString(inputMessage.getBody()),key));
        }

        @Override
        public InputStream getBody() throws IOException {
            return body;
        }

        @Override
        public HttpHeaders getHeaders() {
            return headers;
        }
    }
}
